How does one force construction of a global object in a statically linked library? [MSVC9]

Posted by Peter C O Johansson on Stack Overflow See other posts from Stack Overflow or by Peter C O Johansson
Published on 2010-03-28T11:08:25Z Indexed on 2010/03/28 11:13 UTC
Read the original article Hit count: 240

Filed under:
|

I have a global list of function pointers. This list should be populated at startup. Order is not important and there are no dependencies that would complicate static initialization. To facilitate this, I've written a class that adds a single entry to this list in its constructor, and scatter global instances of this class via a macro where necessary. One of the primary goals of this approach is to remove the need for explicitly referencing every instance of this class externally, instead allowing each file that needs to register something in the list to do it independently. Nice and clean.

However, when placing these objects in a static library, the linker discards (or rather never links in) these units because no code in them is explicitly referenced. Explicitly referencing symbols in the compilation units would be counterproductive, directly contradicting one of the main goals of the approach. For the same reason, /INCLUDE is not an acceptable option, and /OPT:NOREF is not actually related to this problem.

Metrowerks has a __declspec directive for it, GCC has -force_load, but I cannot find any equivalent for MSVC.

© Stack Overflow or respective owner

Related posts about c++

Related posts about msvc